package com.roc.web.action.agent;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.opensymphony.xwork2.ActionContext;
import com.roc.newPage.IPageService;
import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.ModuleCategory;
import com.roc.pojo.Operators;
import com.roc.pojo.ProfitModule;
import com.roc.pojo.ProfitPercentModule;
import com.roc.pojo.ProfitRuleModule;
import com.roc.service.IAgentService;
import com.roc.service.IModelService;
import com.roc.service.ServiceException;
import com.roc.service.operator.IPowerInfoService;
import com.roc.util.Constance;
import com.roc.util.constant.Constant;
import com.roc.util.constant.ProfitModuleStatus;
import com.roc.util.constant.Role;

@Component
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
@Namespace("/model")
public class ProfitModuleAction  extends PaginationBaseAction{
	/**
	 * 
	 */
	private static final long serialVersionUID = 6041070317167514019L;

	private Logger logger=LogManager.getLogger(ProfitModuleAction.class);

	private Long psamCardStartNo;
	private Long psamCardEndNo;
	private Long totalNum;
	
	private ProfitModuleSearchCondition searchCondition;
	private ProfitModule profitModule;
	
	private String modelId;
	
	@Autowired
	IPageService pagenitionService;
	@Autowired
	IModelService modelService;
	@Autowired
	IAgentService  agentService;
	@Autowired
	IPowerInfoService powerInfoService;

	@Action(value = "profitModuleInit", results = {
			@Result(name = "success", location = "/pages/model/profitModuleList.jsp"),
			@Result(name = "error", location = "/error.jsp") }
	)
	public String profitModuleInit() throws Exception {
		Operators loginOperator = (Operators) ActionContext.getContext()
				.getSession().get(Constant.SESSION_LOGIN_MERCHANT);

		if(!loginOperator.getRoleType().equals(Role.AGENT.getCode()) && !loginOperator.getRoleType().equals(Role.SYSTEM.getCode()) 
				&& !loginOperator.getRoleType().equals(Role.OPERATORS_COMM.getCode()) && !loginOperator.getRoleType().equals(Role.OPERATORS_LEAD.getCode())
				 && !loginOperator.getRoleType().equals(Role.O_MANAGER.getCode()) ){
			addActionError("此登陆账号没有权限");
			return ERROR;
		}

		searchCondition = new ProfitModuleSearchCondition();
		return SUCCESS;
	}

	@Action(value = "queryProfitModuleList", results = { @Result(name = "success", location = "/pages/model/profitModuleList.jsp") })
	// 查询代理商统计信息
	public String queryProfitModuleList() throws Exception {

		Operators op = (Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		if (searchCondition == null) {
			searchCondition = (ProfitModuleSearchCondition) getSearchConditionFromSession();
			if (searchCondition == null) {
				searchCondition = new ProfitModuleSearchCondition();
			}
		}
		try {
			if(!op.getRoleType().equals(Role.AGENT.getCode()) && !op.getRoleType().equals(Role.SYSTEM.getCode())
					&& !op.getRoleType().equals(Role.OPERATORS_COMM.getCode()) && !op.getRoleType().equals(Role.OPERATORS_LEAD.getCode())
					&& !op.getRoleType().equals(Role.O_MANAGER.getCode()) ){
				addActionError("此登陆账号没有权限");
				return ERROR;
			}
			org();

			searchCondition.setAgentId(op.getId());
			
			int rows = pagenitionService.countSQL(searchCondition);

			searchRsList = pagenitionService.findAllSQL(searchCondition,
					calcuStart(getCurrentPage()), Constance.PAGE_MAX_SIZE);

			List<ProfitModule> opBeanList = new ArrayList<ProfitModule>();
			
			if (searchRsList != null && searchRsList.size() > 0) {
				Iterator iterator = searchRsList.iterator();
				while (iterator.hasNext()) {
					Object[] obj = (Object[]) iterator.next();
					ProfitModule bean = new ProfitModule();

					if (null != obj[0] && !"".equals( String.valueOf(obj[0]) ) ) {
						bean.setId( Long.valueOf( String.valueOf( obj[0] ) ) ); 
					}
					if (null != obj[1] && !"".equals( String.valueOf(obj[1]) ) ) {
						bean.setModuleName(Constance.Null2EmptyTrim(obj[1])); 
					}
					if ( null != obj[2] && !"".equals( String.valueOf(obj[2]) ) ) {
						bean.setRemark(Constance.Null2EmptyTrim(obj[2])); 
					}
					if ( null != obj[3] && !"".equals( String.valueOf(obj[3]) ) ) {
						bean.setDtCreateStr( Constance.Null2EmptyTrim(obj[3]) );
					}
					if ( null != obj[4] && !"".equals( String.valueOf(obj[4]) ) ) {
						bean.setStatus( Constance.Null2EmptyTrim(obj[4]) );
					}
					opBeanList.add(bean);
				}
			}
			
			searchRsList.clear();
			searchRsList.addAll(opBeanList);
			this.setTotalPage(this.calcuTotalPage(opBeanList.size()));
			addActionMessage("当前条件下统计到【" + rows + "】条记录");
			getRequest().setAttribute(SEARCH_RS_LIST, searchRsList);
			getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
			getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
			setSearchToConditionSession(searchCondition);

		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			addActionError(e.getMessage());
		}

		return SUCCESS;
	}

	@Action(value = "addProfitModule", 
			results = { @Result(name = "success", location = "/pages/model/addProfitModule.jsp"),
			@Result(name = "error", location = "/error.jsp")
    })
	public String addProfitModule(){
		Operators logingOperators = (Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		List<ModuleCategory> moduleList=new ArrayList<ModuleCategory>();
		try{
			profitModule = new ProfitModule();

			Map<String, String> map=powerInfoService.queryRealIdByOpId(logingOperators.getSuperiorId(), logingOperators.getRoleType(), logingOperators.getId(), logingOperators.getOrgCode());
            String opRealId =map.get("opRealId");

			Operators opRealOperator = powerInfoService.loadOperatorsById(new Long(opRealId));
			Map<String, String> mccMap = agentService.getMccArray4Agent(opRealOperator.getAccountNo(),opRealOperator.getRoleType());
			
			getRequest().setAttribute("mccList",mccMap);//mcc
			getRequest().setAttribute("perList",getDefPer());//
			
		}catch(Exception e){
			logger.error(e.getMessage(),e);
			addActionError(e.getMessage());
			return ERROR;
		}
		
		return SUCCESS;
	}
	
	@Action(value = "saveProfitModule", 
			results = {
					@Result(name = SUCCESS,type="chain", location = "queryProfitModuleList"),
					@Result(name = "error", location = "/error.jsp") 
					})
	public String saveProfitModule(){
		Operators logingOperators = (Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		try{
			List<ProfitModule> profitModuleList = modelService.queryProfitModuleByAgentId(String.valueOf(logingOperators.getId()));
			if( null != profitModuleList && profitModuleList.size() >= Constant.MAX_PROFIT_MODULE_SIZE){
				addActionMessage("模板数量超过上限,不可以再添加!");
				return INPUT;
			}
			
			String moduleName = profitModule.getModuleName();
			ProfitModule module = modelService.queryProfitModuleByModuleName(moduleName);

			if(module != null){
				addActionMessage("模板名称【" + module.getModuleName() + "】已存在");
				return INPUT;
			}

			profitModule.setStatus(ProfitModuleStatus.NO.getCode());// 状态, 0普通模板 1 默认模板
			if( null == profitModuleList || profitModuleList.size() == 0){
				// 第一条默认设置为 默认模板
				profitModule.setStatus(ProfitModuleStatus.YES.getCode());// 状态, 0普通模板 1 默认模板
				
			}
			profitModule.setAgentId(logingOperators.getId());
			modelService.saveProfitModuleBatch(logingOperators, profitModule);
			
		}catch(ServiceException e){
			logger.error(e.getMessage(),e);
			addActionError(e.getMessage());
			return ERROR;
		}
		return SUCCESS;
	}
	
	@Action(value = "modifProfitModule", 
			results = { @Result(name = "success", location = "/pages/model/modifProfitModule.jsp"),
			@Result(name = "error", location = "/error.jsp")
    })
	public String modifProfitModule(){
		Operators logingOperators = (Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		try{
		    profitModule = modelService.queryProfitModuleById(logingOperators.getId(), modelId);
			List<ProfitRuleModule> profitRuleModuleList = modelService.queryProfitRuleModule(logingOperators.getId(), modelId);
			Map<String,ProfitRuleModule> ruleMap = dealList(profitRuleModuleList);
			List<ProfitPercentModule> profitPerModuleList = modelService.queryProfitPercentModule(logingOperators.getId(), modelId);
			profitPerModuleList = getNewPreList(profitPerModuleList);
			profitModule.setProfitPerList(profitPerModuleList);

			Map<String, String> map=powerInfoService.queryRealIdByOpId(logingOperators.getSuperiorId(), logingOperators.getRoleType(), logingOperators.getId(), logingOperators.getOrgCode());
            String opRealId =map.get("opRealId");

			Operators opRealOperator = powerInfoService.loadOperatorsById(new Long(opRealId));
			Map<String,String> mccMap = agentService.getMccArray4Agent(opRealOperator.getAccountNo(),opRealOperator.getRoleType());
			
			List<ProfitRuleModule> list = getNewRuleList(mccMap, ruleMap);
			profitModule.setProList(list);

			getRequest().setAttribute("profitModule",profitModule);
			getRequest().setAttribute("mccList",mccMap);
			getRequest().setAttribute("checkRuleMap",ruleMap.keySet());
			getRequest().setAttribute("perList",getDefPer());
			
		}catch(Exception e){
			logger.error(e.getMessage(),e);
			addActionError(e.getMessage());
			return ERROR;
		}
		return SUCCESS;
	}
	
	@Action(value = "saveModifProfitModule", 
			results = { @Result(name = "success",type="redirect", location = "/model/queryProfitModuleList.ct"),
			@Result(name = "error", location = "/error.jsp")
    })
	public String saveModifProfitModule(){
		Operators logingOperators = (Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);

		try{
			ProfitModule oldPro = modelService.queryProfitModuleById(logingOperators.getId(), String.valueOf(profitModule.getId()));
			String newModuleName = profitModule.getModuleName();
			ProfitModule newModule = modelService.queryProfitModuleByModuleName(newModuleName);
			
			if(newModule != null && !oldPro.getModuleName().equals(newModuleName)){
				addActionMessage("模板名称【" + newModule.getModuleName() + "】已存在");
				return INPUT;
			}
			modelService.updateSaveProfitModule(profitModule, logingOperators, oldPro);

		}catch(ServiceException e){
			logger.error(e.getMessage(),e);
			addActionError(e.getMessage());
			return ERROR;
		}

		return SUCCESS;
	}
	
	@Action(value = "delProfitModule", 
			results = { @Result(name = "success",type="redirect", location = "/model/queryProfitModuleList.ct"),
			@Result(name = "error", location = "/error.jsp")
    })
    public String delProfitModule(){
		Operators logingOperators = (Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		
		try{
		    profitModule = modelService.queryProfitModuleById(logingOperators.getId(), modelId);
    		modelService.deleteProfitModule(profitModule, logingOperators);
    	}catch(ServiceException e){
    		logger.error(e.getMessage(),e);
			addActionError(e.getMessage());
			return ERROR;
    	}
		return SUCCESS;
    }


	@Action(value = "setDefaultProfitModule", 
			results = { @Result(name = "success", type="redirect", location = "/model/queryProfitModuleList.ct"),
			@Result(name = "error", location = "/error.jsp")
    })
	public String setDefaultProfitModule(){
		Operators logingOperators = (Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		try{
			modelService.setDefaultProfitModule(modelId,logingOperators.getId());
			
		}catch(ServiceException e){
			logger.error(e.getMessage(),e);
			addActionError(e.getMessage());
			return ERROR;
		}
		
		return SUCCESS;
	}
	
	public List<ProfitRuleModule> getNewRuleList(Map<String,String> mccMap,Map<String,ProfitRuleModule> ruleMap){
		List<ProfitRuleModule> ruleListNew  = new ArrayList<ProfitRuleModule>();
		
		for(Map.Entry<String, String> entry : mccMap.entrySet()) {
			String key = entry.getKey();
			ProfitRuleModule pro = ruleMap.get(key);
			if(pro==null){
				/*pro = new ProfitRule();
				pro.setIsCheck("0");
				pro.setMccTypeName(mccMap.get(key));
				pro.setMccTypeCode(key);	
				*/
			}
			ruleListNew.add(pro);
		}
		return ruleListNew;
		
	}
	public List<ProfitPercentModule> getNewPreList(List<ProfitPercentModule> perList){
		List<ProfitPercentModule> perListNew  = new ArrayList<ProfitPercentModule>();
		for (ProfitPercentModule per : perList) {
			String percentStr = per.getPercent();
			Double perDouble = Double.parseDouble(percentStr) * 100;
			// double 转 int 类型,便于页面显示
			BigDecimal b = new BigDecimal(perDouble);
			int percent = b.intValue();
			
			per.setPercent(percent + "");
			perListNew.add(per);
		}
		return perListNew;
	}
	
	
	public Map<String,ProfitRuleModule> dealList(List<ProfitRuleModule> ruleList){
		Map<String,ProfitRuleModule> backMap = new LinkedHashMap<String, ProfitRuleModule>();
		
		for(ProfitRuleModule pro:ruleList){/*
			String id = pro.getMccTypeCode()+"-"+pro.getParamName1();*/
			String id = pro.getMccTypeCode();
			pro.setIsCheck("1");
			backMap.put(id,pro);
		}
		return backMap;
		
	}
	
	public HashMap<String,String> getDefPer(){
		HashMap<String, String> map = new HashMap<String, String>();
		map.put("01", "01");
		map.put("02", "02");
		map.put("03", "03");
		map.put("04", "04");
		return map;
	}
	// 加载数据
	public void org() throws Exception{

//		getRequest().setAttribute("opList", opList);
	}

	@Override
	protected String getInitPageSize() {
		// TODO Auto-generated method stub
		return Constance.PAGE_MAX_SIZE + "";
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {
		// TODO Auto-generated method stub
		return (ProfitModuleSearchCondition) getSession().getAttribute(
				SEARCH_SESSION_BEAN_TERM_SN_IMPORT);
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass()
			throws Exception {
		// TODO Auto-generated method stub
		return searchCondition;
	}

	@Override
	protected void setSearchConditionToSubClass(
			BaseSearchCondition searchCondition) throws Exception {
		this.setSearchConditionToSubClass(searchCondition);

	}

	@Override
	protected void setSearchToConditionSession(
			BaseSearchCondition searchCondition) {
		getSession().setAttribute(SEARCH_SESSION_BEAN_TERM_SN_IMPORT,
				searchCondition);
	}

	public Long getPsamCardStartNo() {
		return psamCardStartNo;
	}

	public void setPsamCardStartNo(Long psamCardStartNo) {
		this.psamCardStartNo = psamCardStartNo;
	}

	public Long getPsamCardEndNo() {
		return psamCardEndNo;
	}

	public void setPsamCardEndNo(Long psamCardEndNo) {
		this.psamCardEndNo = psamCardEndNo;
	}

	public Long getTotalNum() {
		return totalNum;
	}

	public void setTotalNum(Long totalNum) {
		this.totalNum = totalNum;
	}


	public ProfitModuleSearchCondition getSearchCondition() {
		return searchCondition;
	}

	public void setSearchCondition(ProfitModuleSearchCondition searchCondition) {
		this.searchCondition = searchCondition;
	}

	public ProfitModule getProfitModule() {
		return profitModule;
	}

	public void setProfitModule(ProfitModule profitModule) {
		this.profitModule = profitModule;
	}

	public String getModelId() {
		return modelId;
	}

	public void setModelId(String modelId) {
		this.modelId = modelId;
	}

}
